package com.cloudcc.mobile.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.MediaStore;

import com.cloudcc.cloudframe.model.Album;
import com.cloudcc.mobile.util.photo.Util;

public class ImageCache {
	private static ArrayList<String> getPathList(Context context) {
		ArrayList<String> list = new ArrayList<String>();
		ContentResolver contentResolver = context.getContentResolver();
		String[] projection = new String[] { MediaStore.Images.Media.DATA };
		Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null,
				MediaStore.Images.Media.DATA);
		while (cursor.moveToNext()) {
			list.add(cursor.getString(0));
		}
		cursor.close();
		return list;
	}

	public static ArrayList<Album> getAlbums(Context context) {
		ArrayList<Album> albums = new ArrayList<Album>();
		long start = java.lang.System.currentTimeMillis();
		ArrayList<String> list = getPathList(context);
		long end1 = java.lang.System.currentTimeMillis();
		int size = list.size();
		if (size > 0) {
			String currentDir = "";
			int currentNum = 0;
			String currentUrl = "";
			for (int i = 0; i < size; i++) {
				String path = list.get(i);
				String dirName = Util.getDir(path);
				if ("".equals(currentDir)) {
					currentDir = dirName;
					currentNum = 1;
					currentUrl = path;
					continue;
				}
				if (currentDir.equals(dirName)) {
					currentNum++;
				} else {
					Album album = new Album();
					album.mName = currentDir;
					album.mNum = "(" + currentNum + ")";
					album.mCoverUrl = currentUrl;
					albums.add(album);

					currentDir = dirName;
					currentNum = 1;
					currentUrl = path;
				}
			}
			Album album = new Album();
			album.mName = currentDir;
			album.mNum = "(" + currentNum + ")";
			album.mCoverUrl = currentUrl;
			albums.add(album);
		}
		long end2 = java.lang.System.currentTimeMillis();
		Tools.i("123456","query语句时间----->>>" + (end1 - start) + " 算法时间----->>>" + (end2 - end1));
		return albums;
	}


	
	
	
	
	
	//根据路径压缩
	public static  Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }

	//根据图片压缩
	public static Bitmap comp(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();        
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出    
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}

	//根据质量压缩图片
	public static Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>50) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩        
			baos.reset();//重置baos即清空baos
			options -= 10;//每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}


	//图片存在手机里
	public static String SaveImage(String fileName,byte[] data){
		String state=Environment.getExternalStorageState();
		File file=Environment.getExternalStorageDirectory();
		FileOutputStream outputStream =null;
		File file2=new File(file.getAbsolutePath()+"/CloudCC/Download/Chatter");
		
		if(!file2.exists()){
			file2.mkdirs();
		}
		if(state.equals(Environment.MEDIA_MOUNTED)){
			try {
				outputStream=new FileOutputStream(new File(file2, fileName));
				outputStream.write(data, 0, data.length);
				Tools.i("imageString", file2.getAbsolutePath()+"/"+fileName);
				return file2.getAbsolutePath()+"/"+fileName;
			} catch (Exception e) {
				Tools.handle(e);
			}finally{
				if(outputStream!=null){
					try {
						outputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						Tools.handle(e);
					}
				}
			}

		}
		return "";
	}

	//读取手机里的图片
	public static byte[] readSdcard(String path){
		//首先判断sd卡的状态
		String state=Environment.getExternalStorageState();
		//		获取sd卡的根目录下
		File root=Environment.getExternalStorageDirectory();
		FileInputStream inputStream=null;
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		if(state.equals(Environment.MEDIA_MOUNTED)){
			File file2=new File(path);
			if(file2.exists()){
				try {
					inputStream=new FileInputStream(file2);
					int len=0;
					byte[] bt=new byte[1024];
					while ((len=inputStream.read(bt))!=-1) {
						outputStream.write(bt, 0, len);
					}
					return outputStream.toByteArray();
				} catch (Exception e) {
					Tools.handle(e);
				}finally{
					if(inputStream!=null){
						try {
							inputStream.close();
						} catch (IOException e) {
							Tools.handle(e);
						}
					}
				}
			}
		}
		return null;
	}
	
	public static byte[] getImage(String path){
		byte[] data=null;
		HttpClient httpClient=new DefaultHttpClient();
		HttpPost post=new HttpPost(path);
		try {
			HttpResponse response=httpClient.execute(post);
			if(response.getStatusLine().getStatusCode()==200){
				data=EntityUtils.toByteArray(response.getEntity());
			}
		} catch (Exception e) {
			Tools.handle(e);
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return data;
	}
}
